<template>
    <div >
        <el-form v-bind="cpBindProps"
                 ref="editForm"
                  @submit.native.prevent>
            <slot></slot>
        </el-form>
        <slot name="append"></slot>
    </div>
</template>

<script>

import propStatic from '../props'

export default {
  name: 'XForm',
  provide() {
    return {
      $xform: this
    }
  },
  props: {
    ...propStatic.form
  },
  data() {
    return {
      itemRefMap: new Map(),
      formModel: {},
      errorMessages: {}
    }
  },
  computed: {
    cpBindProps() {
      return {
        model: this.model,
        rules: this.rules,
        inline: this.inline,
        labelPosition: this.labelPosition,
        labelWidth: this.labelWidth,
        labelSuffix: this.labelSuffix,
        hideRequiredAsterisk: this.hideRequiredAsterisk,
        showMessage: this.showMessage,
        inlineMessage: this.inlineMessage,
        statusIcon: this.statusIcon,
        validateOnRuleChange: this.validateOnRuleChange,
        size: this.size,
        disabled: this.disabled,
      }
    }
  },
  methods: {
    setItemRef(field, ref) {
      this.itemRefMap.set(field, ref)
    },
    removeItemRef(field, item) {
      this.itemRefMap.delete(field)
    },
    _clearErrorMessages() {
      this.errorMessages = {}

      this.itemRefMap.forEach((value, key) => {
        value && value.setErrorMessage(null)
      })
    },
    /***************************** el-form 方法开始 ************************************/
    validate(callback) {
      this.$refs.editForm.validate((valid, fiedls) => {
        this._clearErrorMessages()

        // 校验失败
        if (!valid) {
          for (let field of fiedls) {
            let message = fiedls[field].map(o => o.message).join(',')
            this.errorMessages[field] = message


            let itemRef = this.itemRefMap.get(field)
            itemRef && itemRef.setErrorMessage(message)
          }
          let isError = document.getElementsByClassName('is-error')
          isError[0] && isError[0].querySelector('input').focus()

          callback && callback(valid, fiedls)
          return false
        }

        callback && callback({valid, fiedls})
      })
    },
    resetFields() {
      this.$refs.editForm.resetFields()
    },
    clearValidate(callback) {
      this.$refs.editForm.clearValidate(callback)
    },
    /***************************** el-form 方法结束 ************************************/


  },
  created() {

  }
}
</script>

<style scoped>

</style>
